//导入共享数据包
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'

Page({

     //共享数据相关配置
     options: {
        styleIsolation: 'shared'
    },
    
    behaviors: [storeBindingsBehavior],

    //引入需要的共享数据
    storeBindings: {
        store,
        fields: {
            token: 'token',
            userInfo: 'userInfo'
        },
        actions: {

        }
    },

    data: {
      imagePath: 'https://bug-identify-images.oss-cn-beijing.aliyuncs.com/test/00.png',
      pestInfo: {
        type: "正在识别中...",
        accuracy: 0.0,
        description: "正在识别中...",
        markers: [
          {
            points: [
              {x: 10, y: 15},
              {x: 10, y: 170},
              {x: 150, y: 170},
              {x: 150, y: 15}
            ]
          }
        ]
      },
      canvasWidth: 300,
      canvasHeight: 300,
      scale: 1
    },
    
    onLoad: function(options) {
        console.log(options)
        // if (!options.url) {
        //     console.error('缺少必要的URL');
        //     return;
        // }
          console.log(options.url)
          
          //const imagePath = this.data.imagePath;
          wx.request({
            url: 'http://localhost:8980/detect/img', // 注意结尾斜杠
            method: 'POST',
            data: {
              imageUrl: options.url
            },
            header: {
              'content-type': 'application/json', // 默认是 form-urlencoded，建议显式声明
              authentication: store.token
            },
            success: (res) => {
              console.log(res)
              const imgResult = {
                  imagePath: res.data.data.imageUrl,
                  pestInfo: {
                      type: res.data.data.cls,
                      accuracy: res.data.data.conf * 100,
                      description: '未收录', //后续补充
                      markers: [
                        {
                            points: [
                                {x: res.data.data.p1[0], y: res.data.data.p1[1]},
                                {x: res.data.data.p1[0], y: res.data.data.p2[1]},
                                {x: res.data.data.p2[0], y: res.data.data.p2[1]},
                                {x: res.data.data.p2[0], y: res.data.data.p1[1]}
                            ]
                        }
                    ]
                  },
              }
              console.log(imgResult)
              this.setData({
                  imagePath: imgResult.imagePath,
                  pestInfo: imgResult.pestInfo,
              })
              console.log(this.data.pestInfo)
            // 获取图片信息以设置canvas大小
      wx.getImageInfo({
        src: this.data.imagePath,
        success: (res) => {
            console.log("图片回调：")
            console.log(res)
          // 计算缩放比例，使图片宽度不超过屏幕宽度
          const systemInfo = wx.getSystemInfoSync();
          const maxWidth = systemInfo.windowWidth * 0.9;
          const scale = res.width > maxWidth ? maxWidth / res.width : 1;
          
          this.setData({
            canvasWidth: res.width * scale,
            canvasHeight: res.height * scale,
            scale: scale
          }, () => {
            this.drawMarkers(this.data.pestInfo, res.width, res.height);
          });
        }
      });
            }
          })          
          
        //   const imagePath = decodeURIComponent(options.url);
        //   //const pestInfo = JSON.parse(decodeURIComponent(options.data));
        //   const pestInfo = this.data.pestInfo;
          
        //   this.setData({
        //     imagePath: imagePath,
        //     //pestInfo: pestInfo
        //   });
      
      
    },
    
    drawMarkers: function(pestInfo, imgWidth, imgHeight) {

        const markers = pestInfo.markers
        console.log("绘制markers:" + markers)
        if (!markers || markers.length === 0) return;
        
        const ctx = wx.createCanvasContext('pestCanvas');
        const scale = this.data.scale;
      
        markers.forEach(marker => {
          // 在处理每个marker前重置样式
          ctx.setStrokeStyle('#FF0000');  // 红色边框
          ctx.setLineWidth(1);           // 线宽
          ctx.setFillStyle('rgba(255, 0, 0, 0.1)'); // 半透明红色填充
      
          const points = marker.points.map(p => ({
            x: p.x * scale,
            y: p.y * scale
          }));
      
          // 绘制多边形
          ctx.beginPath();
          ctx.moveTo(points[0].x, points[0].y);
          for (let i = 1; i < points.length; i++) {
            ctx.lineTo(points[i].x, points[i].y);
          }
          ctx.closePath();
          ctx.stroke(); // 描边
          ctx.fill();   // 填充
          
          // 设置文本样式
          ctx.setFontSize(16);  // 设置字体大小
          ctx.setFillStyle('#FF0000'); // 文本颜色
      
          // 添加识别信息文本
          console.log(pestInfo)
          const text = `Type: ${pestInfo.type}, Accuracy: ${pestInfo.accuracy}%`;
          ctx.fillText(text, points[1].x, points[1].y + 16); // 调整文本位置避免覆盖
        });
      
        ctx.draw();
      }
  });